<template>
  <div class="payment-audit-page">
    <van-nav-bar title="支付凭证审核" left-arrow @click-left="$router.back()" />
    
    <!-- 统计信息 -->
    <div class="stats-section">
      <van-row>
        <van-col span="8">
          <div class="stat-item">
            <div class="stat-number">{{ stats.pendingCount }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </van-col>
        <van-col span="8">
          <div class="stat-item">
            <div class="stat-number">{{ stats.approvedCount }}</div>
            <div class="stat-label">已通过</div>
          </div>
        </van-col>
        <van-col span="8">
          <div class="stat-item">
            <div class="stat-number">{{ stats.rejectedCount }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
        </van-col>
      </van-row>
    </div>
    
    <!-- 筛选器 -->
    <div class="filter-section">
      <van-tabs v-model:active="activeTab" @change="onTabChange">
        <van-tab title="待审核" name="pending" />
        <van-tab title="已通过" name="approved" />
        <van-tab title="已拒绝" name="rejected" />
      </van-tabs>
    </div>
    
    <!-- 支付凭证列表 -->
    <div class="payment-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div
            v-for="item in paymentList"
            :key="item.id"
            class="payment-item"
            @click="showDetail(item)"
          >
            <div class="payment-header">
              <div class="order-info">
                <div class="order-number">订单号: {{ item.orderNumber }}</div>
                <div class="create-time">{{ formatTime(item.createTime) }}</div>
              </div>
              <div class="status-badge" :class="getStatusClass(item.manualAuditStatus)">
                {{ getStatusText(item.manualAuditStatus) }}
              </div>
            </div>
            
            <div class="payment-content">
              <div class="info-row">
                <span class="label">收款方:</span>
                <span class="value">{{ item.payeeName || '未识别' }}</span>
              </div>
              <div class="info-row">
                <span class="label">支付金额:</span>
                <span class="value">¥{{ item.paymentAmount || '0.00' }}</span>
              </div>
              <div class="info-row">
                <span class="label">商户名称:</span>
                <span class="value">{{ item.merchantName || '未知' }}</span>
              </div>
              <div v-if="item.forceSubmit" class="force-submit-tag">
                <van-icon name="warning-o" />
                <span>强制提交</span>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    
    <!-- 详情弹窗 -->
    <van-dialog
      v-model:show="showDetailDialog"
      title="支付凭证详情"
      :show-confirm-button="false"
      :show-cancel-button="false"
      class="detail-dialog"
    >
      <div v-if="selectedPayment" class="detail-content">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">订单号:</span>
              <span class="value">{{ selectedPayment.orderNumber }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付金额:</span>
              <span class="value">¥{{ selectedPayment.paymentAmount }}</span>
            </div>
            <div class="info-item">
              <span class="label">收款方:</span>
              <span class="value">{{ selectedPayment.payeeName }}</span>
            </div>
            <div class="info-item">
              <span class="label">商户名称:</span>
              <span class="value">{{ selectedPayment.merchantName }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付时间:</span>
              <span class="value">{{ selectedPayment.paymentTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付方式:</span>
              <span class="value">{{ selectedPayment.paymentMethod }}</span>
            </div>
          </div>
        </div>
        
        <!-- 验证结果 -->
        <div class="detail-section">
          <h3>验证结果</h3>
          <div class="verification-info">
            <div class="verification-item">
              <span class="label">收款方匹配:</span>
              <span class="value" :class="selectedPayment.payeeMatch ? 'success' : 'error'">
                {{ selectedPayment.payeeMatch ? '匹配' : '不匹配' }}
              </span>
            </div>
            <div class="verification-item">
              <span class="label">订单号重复:</span>
              <span class="value" :class="selectedPayment.orderDuplicate ? 'error' : 'success'">
                {{ selectedPayment.orderDuplicate ? '重复' : '不重复' }}
              </span>
            </div>
            <div class="verification-item">
              <span class="label">验证状态:</span>
              <span class="value" :class="getVerificationStatusClass(selectedPayment.verificationStatus)">
                {{ getVerificationStatusText(selectedPayment.verificationStatus) }}
              </span>
            </div>
          </div>
        </div>
        
        <!-- 强制提交信息 -->
        <div v-if="selectedPayment.forceSubmit" class="detail-section">
          <h3>强制提交信息</h3>
          <div class="force-submit-info">
            <div class="info-item">
              <span class="label">提交原因:</span>
              <span class="value">{{ selectedPayment.forceSubmitReason }}</span>
            </div>
            <div v-if="selectedPayment.userRemark" class="info-item">
              <span class="label">用户备注:</span>
              <span class="value">{{ selectedPayment.userRemark }}</span>
            </div>
          </div>
        </div>
        
        <!-- 审核信息 -->
        <div v-if="selectedPayment.manualAuditStatus !== 'pending'" class="detail-section">
          <h3>审核信息</h3>
          <div class="audit-info">
            <div class="info-item">
              <span class="label">审核状态:</span>
              <span class="value" :class="getStatusClass(selectedPayment.manualAuditStatus)">
                {{ getStatusText(selectedPayment.manualAuditStatus) }}
              </span>
            </div>
            <div v-if="selectedPayment.auditorName" class="info-item">
              <span class="label">审核人:</span>
              <span class="value">{{ selectedPayment.auditorName }}</span>
            </div>
            <div v-if="selectedPayment.manualAuditTime" class="info-item">
              <span class="label">审核时间:</span>
              <span class="value">{{ formatTime(selectedPayment.manualAuditTime) }}</span>
            </div>
            <div v-if="selectedPayment.manualAuditRemark" class="info-item">
              <span class="label">审核备注:</span>
              <span class="value">{{ selectedPayment.manualAuditRemark }}</span>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div v-if="selectedPayment.manualAuditStatus === 'pending'" class="action-buttons">
          <van-button
            type="danger"
            size="large"
            @click="auditPayment('rejected')"
            :loading="auditing"
          >
            拒绝
          </van-button>
          <van-button
            type="primary"
            size="large"
            @click="auditPayment('approved')"
            :loading="auditing"
          >
            通过
          </van-button>
        </div>
      </div>
    </van-dialog>
    
    <!-- 审核备注弹窗 -->
    <van-dialog
      v-model:show="showAuditDialog"
      title="审核备注"
      :show-confirm-button="false"
      :show-cancel-button="false"
    >
      <div class="audit-dialog-content">
        <van-field
          v-model="auditRemark"
          type="textarea"
          placeholder="请输入审核备注（可选）"
          rows="4"
          maxlength="500"
          show-word-limit
        />
        <div class="dialog-actions">
          <van-button @click="showAuditDialog = false">取消</van-button>
          <van-button type="primary" @click="confirmAudit">确定</van-button>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import axios from 'axios'

// 响应式数据
const activeTab = ref('pending')
const paymentList = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const showDetailDialog = ref(false)
const showAuditDialog = ref(false)
const selectedPayment = ref(null)
const auditRemark = ref('')
const auditing = ref(false)
const currentPage = ref(0)
const pageSize = ref(20)

// 统计数据
const stats = ref({
  pendingCount: 0,
  approvedCount: 0,
  rejectedCount: 0
})

// 计算属性
const getStatusClass = (status) => {
  const statusMap = {
    pending: 'status-pending',
    approved: 'status-approved',
    rejected: 'status-rejected'
  }
  return statusMap[status] || 'status-pending'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || '未知'
}

const getVerificationStatusClass = (status) => {
  const statusMap = {
    verified: 'success',
    failed: 'error',
    manual_review: 'warning'
  }
  return statusMap[status] || 'warning'
}

const getVerificationStatusText = (status) => {
  const statusMap = {
    verified: '已验证',
    failed: '验证失败',
    manual_review: '人工审核中'
  }
  return statusMap[status] || '未知'
}

// 方法
const loadPaymentList = async (page = 0, reset = false) => {
  try {
    loading.value = true
    
    const response = await axios.get('/v1/payment-proof/admin/pending-audit', {
      params: {
        page,
        size: pageSize.value,
        status: activeTab.value
      }
    })
    
    if (response.data.success) {
      const newData = response.data.data.content || []
      
      if (reset) {
        paymentList.value = newData
      } else {
        paymentList.value.push(...newData)
      }
      
      finished.value = newData.length < pageSize.value
      currentPage.value = page
    } else {
      showToast(response.data.message || '加载失败')
    }
  } catch (error) {
    console.error('加载支付凭证列表失败:', error)
    showToast('加载失败，请稍后重试')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

const onLoad = () => {
  loadPaymentList(currentPage.value + 1)
}

const onRefresh = () => {
  loadPaymentList(0, true)
}

const onTabChange = () => {
  loadPaymentList(0, true)
}

const showDetail = (payment) => {
  selectedPayment.value = payment
  showDetailDialog.value = true
}

const auditPayment = async (status) => {
  try {
    await showConfirmDialog({
      title: '确认审核',
      message: `确定要${status === 'approved' ? '通过' : '拒绝'}此支付凭证吗？`
    })
    
    showDetailDialog.value = false
    showAuditDialog.value = true
    pendingAuditStatus.value = status
  } catch (error) {
    // 用户取消
  }
}

const pendingAuditStatus = ref('')

const confirmAudit = async () => {
  try {
    auditing.value = true
    
    const response = await axios.post(`/v1/payment-proof/admin/manual-audit/${selectedPayment.value.id}`, null, {
      params: {
        auditStatus: pendingAuditStatus.value,
        auditRemark: auditRemark.value
      }
    })
    
    if (response.data.success) {
      showToast('审核完成')
      showAuditDialog.value = false
      auditRemark.value = ''
      
      // 刷新列表
      loadPaymentList(0, true)
    } else {
      showToast(response.data.message || '审核失败')
    }
  } catch (error) {
    console.error('审核失败:', error)
    showToast('审核失败，请稍后重试')
  } finally {
    auditing.value = false
  }
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 生命周期
onMounted(() => {
  loadPaymentList(0, true)
})
</script>

<style scoped>
.payment-audit-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.stats-section {
  background: white;
  padding: 20px;
  margin-bottom: 10px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.filter-section {
  background: white;
  margin-bottom: 10px;
}

.payment-list {
  padding: 0 15px;
}

.payment-item {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.order-info {
  flex: 1;
}

.order-number {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.create-time {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-approved {
  background: #d4edda;
  color: #155724;
}

.status-rejected {
  background: #f8d7da;
  color: #721c24;
}

.payment-content {
  font-size: 14px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.label {
  color: #666;
}

.value {
  color: #333;
  font-weight: 500;
}

.force-submit-tag {
  display: inline-flex;
  align-items: center;
  background: #fff3cd;
  color: #856404;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 8px;
}

.force-submit-tag .van-icon {
  margin-right: 4px;
}

.detail-dialog .van-dialog__content {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-item .label {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.info-item .value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.verification-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.verification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.verification-item .success {
  color: #28a745;
  font-weight: bold;
}

.verification-item .error {
  color: #dc3545;
  font-weight: bold;
}

.verification-item .warning {
  color: #ffc107;
  font-weight: bold;
}

.force-submit-info {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
}

.audit-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.action-buttons .van-button {
  flex: 1;
}

.audit-dialog-content {
  padding: 20px;
}

.dialog-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.dialog-actions .van-button {
  flex: 1;
}
</style>

